using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DrawingCore;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

using Read.Models;
using Read.Models.Models;
using Read.Services;
using Read.Utility;

namespace Read.Web.Admin
{
    /// <summary>
    /// 账户管理
    /// </summary>
    [Area("Admin")]
    public class AccountController : Controller
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public IActionResult Login(string ReturnUrl)
        {
            ViewBag.code = HttpContext.Session.GetString(ConfigService.SessionKey);
            ViewBag.returnUrl = ReturnUrl;
            return View();
        }
        /// <summary>
        /// 执行登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<IActionResult> LoginDo(AdminModel user)
        {
            // user.UserName = "xiong"; user.Password = "123456"; user.RoleId = 2;
            //判断验证码是否正确
            // if (!validateCode(user.Verify))
            // {
            //     return Json(new ResultData<string>() { Result = false, Message = "验证码错误!" });
            // }

            //执行登录
            var res = new AccountService().loginCheck(user);
            if (res.Code == 0)
            {
                //写入登录票据
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Name, res.Data.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, res.Data.RoleId.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(res.Data)));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
                {
                    IsPersistent = false,
                    ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromDays(1))
                });
            }
            #region 操作日志
            var service = new LogService();
            var log = new LoginLogModel();
            log.UserName = user.UserName;
            log.Time = Tools.ToUnixTime();
            log.Ip = HttpContext.GetClientIP();
            log.Status = res.Result;
            log.Info = res.Message;
            log.PassWord = res.Result == true ? "密码保密" : user.Password;
            service.loginLogAdd(log);
            #endregion
            return Json(res);
        }

        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        public IActionResult Code()
        {
            ValidateCode vch = new ValidateCode();
            string code = vch.GetRandomNumberString(4);
            HttpContext.Session.SetString(ConfigService.SessionKey, code.ToLower());
            return File(vch.CreateImage(code), "image/jpeg");
        }

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private bool validateCode(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return false;
            }
            var sessionCode = HttpContext.Session.GetString(ConfigService.SessionKey);
            return sessionCode != null && sessionCode == code.Trim().ToLower();
        }

        /// <summary>
        /// 无权访问
        /// </summary>
        /// <returns></returns>
        public IActionResult AccessDenied()
        {
            return Content("无权访问");
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Redirect("/Admin");
        }
    }
}